const fs = require('fs')
const path = require('path')
const yaml = require('js-yaml');
const { upload, multipartUpload } = require('./utils')

const importChalk = () => import('chalk').then(({default: chalk}) => chalk);
const log = console.log;

const args = process.argv.filter(v => v.startsWith('--'))

const platform = args[0].replace('--', '')
const releasePath = path.join(process.cwd(), 'dist')

const releaseResolve = (dir) => {
    return path.resolve(releasePath, ".", dir)
}

const yamlPath = releaseResolve(platform == 'win' ? 'latest.yml' : `latest-${platform}.yml`)

async function bootstrap(){
  const chalk = await importChalk();

  let yamlDoc = yaml.load(fs.readFileSync(yamlPath, 'utf8'));

  const uploadRequests = yamlDoc.files.map(file => {
    return multipartUpload(releaseResolve(file.url)).then(res => ({ ...res, url: file.url }))
  })

  const responses = await Promise.all(uploadRequests)

  yamlDoc.files = yamlDoc.files.map(file => {
    file.url = responses.find(v => v.url == file.url).fileUrl
    return file
  })

  yamlDoc.path = responses.find(v => v.url == yamlDoc.path).fileUrl

  const yamlString = `
version: ${yamlDoc.version}
files:
${yamlDoc.files.map(file => `  - url: ${file.url}
    sha512: ${file.sha512}
    size: ${file.size}`).join('\n')}
path: ${yamlDoc.path}
sha512: ${yamlDoc.sha512}
releaseDate: '${yamlDoc.releaseDate}'
`.trim();

  // 替换yml内容
  fs.writeFileSync(yamlPath, yamlString)

  try{
      await upload(yamlPath)
  }catch(e){
      console.log(e)
      log(chalk.blue.bgRed.bold('上传失败'))
      return
  }
}

bootstrap()
